import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Example12_1 {
    public static void main(String args[]) {
        WindowButton_1 win=new WindowButton_1("猜数字");
    }
}
class WindowButton_1 extends JFrame{
    int number;
    JLabel hintLabel;
    JTextField inputGuess;
    JButton buttonGetNumber,buttonEnter;
    WindowButton_1(String s) {
        super(s);
        addWindowListener( new WindowAdapter(){ //匿名类的实例监视窗口事件
                               public void windowClosing(WindowEvent e) {
                                   dispose();
                               }
                           }
        );
        setLayout(new FlowLayout());
        buttonGetNumber=new JButton("得到一个随机数");
        add(buttonGetNumber);
        hintLabel=new JLabel("输入你的猜测：",JLabel.CENTER);
        hintLabel.setBackground(Color.cyan);
        inputGuess=new JTextField("0",10);
        add(hintLabel);
        add(inputGuess);
        buttonEnter=new JButton("确定");
        add(buttonEnter);
        buttonEnter.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int guess=0;
                try {  guess=Integer.parseInt(inputGuess.getText());
                    if(guess==number) {
                        hintLabel.setText("猜对了！");
                    }
                    else if(guess>number) {
                        hintLabel.setText("猜大了！");
                        inputGuess.setText(null);
                    }
                    else if(guess<number) {
                        hintLabel.setText("猜小了！");
                        inputGuess.setText(null);
                    }
                }
                catch(NumberFormatException event) {
                    hintLabel.setText("请输入数字字符");
                }
            }
        });
        buttonGetNumber.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                number=(int)(Math.random()*100)+1;
                hintLabel.setText("输入你的猜测：");
            }
        });
        setBounds(100,100,150,150);
        setVisible(true);
        validate();
    }
}
